import Global from "./Global"
import cjs=createjs
import DrawDebugRectEvent from "./events/DrawDebugRectEvent"
import { TouchEvent, ViewEvent } from "./Const"
//import createjs from "../createjs"
interface Listener{
    (e?:cjs.MouseEvent):void
}
export default class ButtonHelper {
    private target:cjs.DisplayObject
    private listenerMap=new Map<string,Listener[]>()
    constructor(target:cjs.DisplayObject){
        this.target=target
        
        //wx.onTouchStart(this.onTouchStart.bind(this))
    }
    on(type:string,listener:Listener):void{
        switch(type){
            case TouchEvent.TOUCH_START:
                wx.onTouchStart(this.onTouchStart.bind(this))
                this.putListener(type,listener)
                break
            case TouchEvent.TOUCH_START:
                wx.onTouchEnd(this.onTouchEnd.bind(this))
                this.putListener(type,listener)
                break
        }
        
    }
    off(type:string,listener:Listener){
        const arr=this.listenerMap.get(type)
        const i=arr.indexOf(listener)
        if(i!=-1){
            arr.splice(i,1)
        }
    }
    private putListener(type:string,listener:Listener):void{
        let arr=this.listenerMap.get(type)
        if(arr==undefined){
            this.listenerMap.set(type,new Array<Listener>())
        }
        arr=this.listenerMap.get(type)
        if(arr.indexOf(listener)==-1){
            arr.push(listener)
        }
    }
    private onTouchStart(res:any):void{
        if(this.target.visible==false)return
        if(this.hitTest(res)){
            const arr=this.listenerMap.get(TouchEvent.TOUCH_START)
            arr.forEach((item:Listener)=>{
                item()
            })
        }
    }
    private onTouchEnd(res:any):void{
        if(this.target.visible==false)return
        if(this.hitTest(res)){
            const arr=this.listenerMap.get(TouchEvent.TOUCH_END)
            arr.forEach((item:Listener)=>{
                item()
            })
        }
    }
    private hitTest(res:any):boolean{
        const {clientX,clientY}=res.touches[0]
        const scale=Global.scale
        const x=clientX/scale
        const y=clientY/scale
        const p=this.target.localToGlobal(0,0)
        const rect=this.target.getBounds()
        rect.x=p.x/scale
        rect.y=p.y/scale
        if(x>rect.x&&x<(rect.x+rect.width)&&y>rect.y&&y<(rect.y+rect.height)){
            //this.target.dispatchEvent(new DrawDebugRectEvent(ViewEvent.DRAW_DEBUG,rect,true))
            return true
        }
        return false
    }
}